<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';

const { baseURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const frameSrc = ref('');
const frameRef = ref<HTMLIFrameElement | null>(null);
const selectedCoordinates = ref<{ lat: number; lng: number } | null>(null);
const locationData = ref();
const onMessage = (event: MessageEvent) => {
  // console.log(event);
  // // 验证消息来源
  // if (event.origin !== 'https://your-tiangmap-domain.com') return;
  const data = event.data;
  if (data.type === 'coordinateSelected') {
    selectedCoordinates.value = data.payload;
    locationData.value = `${data.payload.lng},${data.payload.lat}`;
  }
};
const [Modal, ModalApi] = useVbenModal({
  footer: true,
  onBeforeClose() {
    if (frameRef.value) {
      ModalApi.setData({
        location: locationData.value,
      });
    }
  },
  onConfirm() {
    ModalApi.close();
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      const modalData: any = await ModalApi.getData();
      frameSrc.value = `${baseURL}/admin/dialog/map.html?location=${modalData.value}`;
      locationData.value = modalData.value;
      window.addEventListener('message', onMessage);
    }
  },
});
</script>

<template>
  <Modal class="w-4/5">
    <div class="frame">
      <iframe ref="frameRef" :src="frameSrc" class="simulator-pc"></iframe>
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
.frame {
  z-index: 998;
  height: calc(70vh - 88px);

  .simulator-pc {
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - 88px);
    overflow: hidden;
    border: 0;
  }

  .simulator-pad {
    width: 1180px;
    height: 820px;
    margin: auto;
    border: 1px solid #aaa;
    transform: scale(0.7);
  }

  .simulator-mobile {
    width: 375px;
    height: 667px;
    margin: auto;
    border: 1px solid #aaa;
    transform: scale(0.9);
  }
}

.main-content {
  margin: 2px 0 0 !important;
}
</style>
